package com.wzm.service;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.wzm.bean.DownInfo;
import com.wzm.bean.PicInfo;
import com.wzm.cache.ConfigCache;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.Tag;
import com.wzm.moviepic.AppApplication;
import com.wzm.utils.FileUtils;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;

public class DownService extends Service{
	//private FinalHttp fh = null;
	
	private Context mContext;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		
		super.onCreate();
		
		mContext = this;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		
		//Logger.info("onStart");
		if(intent==null)
		{
			return;
		}
		
		//如果没有网络
		if(AppApplication.mNetWorkState == NetworkUtils.NETWORN_NONE)
		{
			Logger.error("没有网络");
			return;
		}
		
		
		
		
		String action = intent.getStringExtra("action");
		
		if(action.equals(Tag.DownPicList))
		{//下载图片列表
			//获取电影的图片列表
			final String movieid = intent.getStringExtra("movieid");
			
			int curDownMovie = AppApplication.getInstance().getCurDownMovie();
			if(curDownMovie!=0)
			{
				Logger.info("电影："+curDownMovie+"正在下载中,请稍后...");
				return;
			}else{
				//设置上一个下载电影
				//AppApplication.getInstance().getDMap().get(String.valueOf(curDownMovie)).setState(state)
				Logger.error("curDownMovie:"+curDownMovie);
			}
			
			//if()
			
			AppApplication.getInstance().setCurDownMovie(Integer.valueOf(movieid));
			
			String cacheMoviePics = ConfigCache.getUrlCache(AppConfig.GETMOVIEINFO+movieid);
	        if(cacheMoviePics==null)
	        {
	        	AjaxParams params = new AjaxParams();
	    		params.put("movieid",movieid);

	    		FinalHttp fh = new FinalHttp();
	        	fh.post(AppConfig.GETMOVIEINFO, params,new AjaxCallBack<Object>() {
	        		
					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						//super.onSuccess(t);
						String content = t.toString();
						//获取下载电影的图片列表
						ArrayList<PicInfo> pList = excuteJson(content,movieid);
						//加入电影下载队列
						AppApplication.getInstance().addMovie(movieid, pList);
						
						//int curPage = AppApplication.getInstance().getCurPage();
						//int curMovie = AppApplication.getInstance().getCurMovie();
						
						DownInfo di = AppApplication.getInstance().getDMap().get(movieid);
						//di.setCurpage(0);
						di.setSize(pList.size());
						//设置下载中状态
						di.setState(1);
						
						long rowid = DBHelper.getInstance(DownService.this).updateDownInfoSize(movieid, di.getCurpage(), di.getSize());
						if(rowid==1)
						{
							Logger.info("数据库更新图片数组大小成功2");
						}
//						ArrayList<DownInfo> dList = AppApplication.getInstance().getDownList();
//						if(dList.size()>0)
//						{
//							
//							AppApplication.getInstance().getDownList().get(curMovie).setCurpage(curPage);
//							AppApplication.getInstance().getDownList().get(curMovie).setSize(pList.size());
//							
//							AppApplication.getInstance().addMovie(movieid, pList);
							//Logger.error("获取列表成功"+movieid);
							//更新界面
							Intent uiintent = new Intent(Tag.UPDATEUI);
					        sendBroadcast(uiintent); 
					        uiintent = null;
					        
					        //开始下载
//					        Intent service = new Intent(Tag.START);
//							service.putExtra("action", Tag.DownPic);
//							service.putExtra("movieid", movieid);
//						    startService(service);
					        
					        //开始下载
					        Intent service = new Intent(Tag.START);
							service.putExtra("action", Tag.DownPic);
							service.putExtra("movieid", movieid);
						    startService(service);
					        
//						}
					}
	        		
				});
	        }else{
	        	//本地有缓存
	        	ArrayList<PicInfo> pList = excuteJson(cacheMoviePics,movieid);
	        	//Logger.info(":"+pList.size());
	        	//加入电影下载队列
				AppApplication.getInstance().addMovie(movieid, pList);
	        	
	        	
				DownInfo di = AppApplication.getInstance().getDMap().get(movieid);
				di.setSize(pList.size());
				di.setState(1);
				
				long rowid = DBHelper.getInstance(DownService.this).updateDownInfoSize(movieid, di.getCurpage(), di.getSize());
//				if(rowid==1)
//				{
//					Logger.info("数据库更新图片大小成功3");
//				}
				
				
				//更新界面
				Intent uiintent = new Intent(Tag.UPDATEUI);
		        sendBroadcast(uiintent); 
				
//				int curPage = AppApplication.getInstance().getCurPage();
//				int curMovie = AppApplication.getInstance().getCurMovie();
//				
//				ArrayList<DownInfo> dList = AppApplication.getInstance().getDownList();
//				if(dList.size()>0)
//				{
//					AppApplication.getInstance().getDownList().get(curMovie).setCurpage(curPage);
//					AppApplication.getInstance().getDownList().get(curMovie).setSize(pList.size());
//					AppApplication.getInstance().addMovie(movieid, pList);
//					Logger.error("获取列表成功");
//					Intent upintent = new Intent(Tag.UPDATEUI);
//			        sendBroadcast(upintent); 
//			        
//			        
			        //开始下载
			        Intent service = new Intent(Tag.START);
					service.putExtra("action", Tag.DownPic);
					service.putExtra("movieid", movieid);
				    startService(service);
//				}
	        }
	        
	        
	        
		}else if(action.equals(Tag.DownPic))
		{//下载图片
			
			final String movieid = intent.getStringExtra("movieid");
			//获取下载队列
			final ArrayList<PicInfo> pList = AppApplication.getInstance().getFileMap().get(movieid);
			final DownInfo di = AppApplication.getInstance().getDMap().get(movieid);
			
			
			if(di==null)
			{
				Logger.info("di 为空");
				return;
			}
			
			
			//暂停
			if(di.getState()==0)
			{
				Logger.info(movieid+"已暂停");
				//stopSelf();
				return;
			}
			
			
			
			
			int curPage = di.getCurpage();
			
			//Logger.info(obj)
			
			if(curPage>=pList.size())
			{
				Logger.error(curPage+"vs"+pList.size());
				Logger.info("数组越界");
				return;
			}
			
			
			PicInfo pi = pList.get(curPage);
			
			//图片文件夹保存的位置
	    	String fileDirPath = Environment.getExternalStorageDirectory().getPath()+AppConfig.MOVIESDIR+movieid+"/";
	    	//图片名
	    	String filename =  pi.getImage().substring(pi.getImage().lastIndexOf("/")+1);
	    	//创建目录
	    	File movieDir = new File(fileDirPath);
			if(!movieDir.exists())
			{
				movieDir.mkdirs();
			}else{
				if(!movieDir.isDirectory())
				{
					movieDir.mkdirs();
				}
			}
			
			if(pList!=null&&pList.size()>0)
			{
				File imgFile = new File(fileDirPath+filename);
				if(imgFile.exists())
				{//如果文件存在
					//下载下一张图片	
					if(curPage<pList.size()-1)
					{
						//Logger.info("文件存在"+curPage);
						curPage++;
						AppApplication.getInstance().getDMap().get(movieid).setCurpage(curPage);
						
						long updateRow = DBHelper.getInstance(this).updateDownInfo(movieid,curPage,0);

						
						
						Intent upintent = new Intent(Tag.UPDATEUI);
				        sendBroadcast(upintent); 
						
						//继续下一章
						Intent service = new Intent(Tag.START);
						service.putExtra("action", Tag.DownPic);
						service.putExtra("movieid", movieid);
					    startService(service);			
					}else{
						//下载完成
						AppApplication.getInstance().setCurDownMovie(0);
						//计算文件夹大小
						long filesize = getDirSize(movieid);
						
						
						
						
						//记录数据，更新当前页面和下载完成状态
						long updateRow = DBHelper.getInstance(this).updateDownInfo(movieid,curPage,1,filesize);
						if(updateRow==1)
						{//下载完成，更新成功
							Logger.info("下载完成,更新成功");
							//AppApplication.getInstance().getDMap().remove(movieid);
							ArrayList<DownInfo> dList = AppApplication.getInstance().getDownList();
							
							int curDownid = AppApplication.getInstance().getCurDownid();
							

							
					        
							if(curDownid<=dList.size()-1)
							{
								Logger.error("文件存在，下载完成，进行下一个数据下载");
								curDownid = curDownid+1;
								if(curDownid<=dList.size()-1)
								{
									AppApplication.getInstance().setCurDownid(curDownid);
									
									Intent upintent = new Intent(Tag.UPDATEUI);
							        sendBroadcast(upintent);
									
									//启动下一个下载任务服务
									Intent service = new Intent(Tag.START);
									service.putExtra("action", Tag.DownPicList);
									service.putExtra("movieid", dList.get(AppApplication.getInstance().getCurDownid()).getMovieid());
									startService(service);
								}else{
									
									Logger.info("没有下载任务111");
									//Intent upintent = new Intent(Tag.UPDATEUI);
							        //sendBroadcast(upintent);
									AppApplication.getInstance().setCurDownMovie(0);
								}
								
										
							}else{
								Logger.info("没有下载任务111222");
								//Intent upintent = new Intent(Tag.UPDATEUI);
						        //sendBroadcast(upintent);
								AppApplication.getInstance().setCurDownMovie(0);
							}
						}
						

					}
					return;
				}
				
				
			}
			

	    	

			

	
			//如果不存在,下载
			FinalHttp fh = new FinalHttp();
			
			Logger.info("lenght:"+pi.getImage().length());
			//如果图片地址为空
			if(pi.getImage().length()<5||pi.getImage()==null)
			{
				curPage = di.getCurpage();				
				if(curPage<pList.size()-1)
				{
					//Logger.info("图片下载完成"+curPage);
					curPage++;
					AppApplication.getInstance().getDMap().get(movieid).setCurpage(curPage);
					
					long updateRow = DBHelper.getInstance(DownService.this).updateDownInfo(movieid,curPage,0);
//					
//					AppApplication.getInstance().setCurPage(curPage);	
//					AppApplication.getInstance().getDownList().get(curMovie).setCurpage(curPage+1);
					
					
					Intent upintent = new Intent(Tag.UPDATEUI);
			        sendBroadcast(upintent); 
					
					//继续下一张图片
					Intent service = new Intent(Tag.START);
					service.putExtra("action", Tag.DownPic);
					service.putExtra("movieid", movieid);
				    startService(service);			
				}else{
					//下载完成
					
					AppApplication.getInstance().setCurDownMovie(0);
					long filesize = getDirSize(movieid);
					long updateRow = DBHelper.getInstance(DownService.this).updateDownInfo(movieid,curPage,1,filesize);
					Logger.error("下载完成@@@@@@@@@@@@@@@@@@更新："+updateRow);
					
					ArrayList<DownInfo> dList = AppApplication.getInstance().getDownList();
					//dList.remove(0);
					int curDownid = AppApplication.getInstance().getCurDownid();
					
					
			        
					if(curDownid<=dList.size()-1)
					{

				        
						curDownid = curDownid+1;
						if(curDownid<=dList.size()-1)
						{

							AppApplication.getInstance().setCurDownid(curDownid);		
							
							
							Intent upintent = new Intent(Tag.UPDATEUI);
					        sendBroadcast(upintent); 
					        
							//启动下一个下载任务服务
							Intent service = new Intent(Tag.START);
							service.putExtra("action", Tag.DownPicList);
							service.putExtra("movieid", dList.get(AppApplication.getInstance().getCurDownid()).getMovieid());
							startService(service);
						}else{
							Logger.info("没有下载任务22");
							AppApplication.getInstance().setCurDownMovie(0);
						}
						
					}else{
						
						Logger.info("没有下载任务20");
						AppApplication.getInstance().setCurDownMovie(0);
					}
				}
			}else{
				
				Logger.debug("pi.getImage():"+pi.getImage()+""+fileDirPath+filename+"curPage:"+curPage);
				fh.download(pi.getImage(), fileDirPath+filename,true, new AjaxCallBack<File>() {

					@Override
					public void onSuccess(File t) {
						// TODO Auto-generated method stub
						
						int curPage = di.getCurpage();
						
						if(curPage<pList.size()-1)
						{
							//Logger.info("图片下载完成"+curPage);
							curPage++;
							AppApplication.getInstance().getDMap().get(movieid).setCurpage(curPage);
							
							long updateRow = DBHelper.getInstance(DownService.this).updateDownInfo(movieid,curPage,0);
//							
//							AppApplication.getInstance().setCurPage(curPage);	
//							AppApplication.getInstance().getDownList().get(curMovie).setCurpage(curPage+1);
							
							
							Intent upintent = new Intent(Tag.UPDATEUI);
					        sendBroadcast(upintent); 
							
							//继续下一张图片
							Intent service = new Intent(Tag.START);
							service.putExtra("action", Tag.DownPic);
							service.putExtra("movieid", movieid);
						    startService(service);			
						}else{
							//下载完成
							
							AppApplication.getInstance().setCurDownMovie(0);
							long filesize = getDirSize(movieid);
							long updateRow = DBHelper.getInstance(DownService.this).updateDownInfo(movieid,curPage,1,filesize);
							Logger.error("下载完成@@@@@@@@@@@@@@@@@@更新："+updateRow);
							
							ArrayList<DownInfo> dList = AppApplication.getInstance().getDownList();
							//dList.remove(0);
							int curDownid = AppApplication.getInstance().getCurDownid();
							
							
					        
							if(curDownid<=dList.size()-1)
							{

						        
								curDownid = curDownid+1;
								if(curDownid<=dList.size()-1)
								{

									AppApplication.getInstance().setCurDownid(curDownid);		
									
									
									Intent upintent = new Intent(Tag.UPDATEUI);
							        sendBroadcast(upintent); 
							        
									//启动下一个下载任务服务
									Intent service = new Intent(Tag.START);
									service.putExtra("action", Tag.DownPicList);
									service.putExtra("movieid", dList.get(AppApplication.getInstance().getCurDownid()).getMovieid());
									startService(service);
								}else{
									Logger.info("没有下载任务22");
									AppApplication.getInstance().setCurDownMovie(0);
								}
								
							}else{
								
								Logger.info("没有下载任务20");
								AppApplication.getInstance().setCurDownMovie(0);
							}
						}
						
					}

					//下载失败
					@Override								
					public void onFailure(Throwable t, String strMsg) {
						// TODO Auto-generated method stub
						//super.onFailure(t, strMsg);
						Logger.error("下载失败"+strMsg);
						
						if(NetworkUtils.getNetworkState(mContext)==0)
						{//如果是网络断了
							Logger.info("网络中断，停止下载服务");
							AppApplication.mNetWorkState = 0;
							Intent upintent = new Intent(Tag.UPDATEUI);
					        sendBroadcast(upintent); 
							stopSelf();
						}else{
							
							int curPage = di.getCurpage();
							if(curPage<pList.size()-1)
							{//继续下一张
								curPage++;
								AppApplication.getInstance().getDMap().get(movieid).setCurpage(curPage);	
								long updateRow = DBHelper.getInstance(DownService.this).updateDownInfo(movieid,curPage,0);
								//Logger
								
								Intent upintent = new Intent(Tag.UPDATEUI);
						        sendBroadcast(upintent);
								
								Intent service = new Intent(Tag.START);
								service.putExtra("action", Tag.DownPic);
								service.putExtra("movieid", movieid);
							    startService(service);			
							}else{
								//下一个任务							
								ArrayList<DownInfo> dList = AppApplication.getInstance().getDownList();
								//dList.remove(0);
								int curDownid = AppApplication.getInstance().getCurDownid();
								
								if(curDownid<=dList.size()-1)
								{
									AppApplication.getInstance().setCurDownid();
									Intent upintent = new Intent(Tag.UPDATEUI);
							        sendBroadcast(upintent); 
									//启动下一个下载任务服务
									Intent service = new Intent(Tag.START);
									service.putExtra("action", Tag.DownPicList);
									service.putExtra("movieid", dList.get(curDownid).getMovieid());
									startService(service);
								}else{
									Logger.info("没有下载任务3");
									AppApplication.getInstance().setCurDownMovie(0);
								}
								
							}	
						} 	
					}		
				});	
			}
			
	    			
	    		    	
		}else if(action.equals(Tag.StartMovie))
		{//开始新的下载
			Logger.error("XXXXX:"+Tag.StartMovie);
			
			final String movieid = intent.getStringExtra("movieid");			
			int curDownMovie = AppApplication.getInstance().getCurDownMovie();
			if(curDownMovie!=0)
			{
				//Logger.info("电影："+curDownMovie+"正在下载中,请稍后...");
				AppApplication.getInstance().getDMap().get(String.valueOf(curDownMovie)).setState(0);
				//AppApplication.getInstance().getDMap().get(movieid).setState(1);
				//return;
			}
			AppApplication.getInstance().getDMap().get(movieid).setState(1);
			AppApplication.getInstance().setCurDownMovie(Integer.valueOf(movieid));
			
			String cacheMoviePics = ConfigCache.getUrlCache(AppConfig.GETMOVIEINFO+movieid);
	        if(cacheMoviePics==null)
	        {
	        	AjaxParams params = new AjaxParams();
	    		params.put("movieid",movieid);

	    		FinalHttp fh = new FinalHttp();
	        	fh.post(AppConfig.GETMOVIEINFO, params,new AjaxCallBack<Object>() {
	        		
					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						//super.onSuccess(t);
						String content = t.toString();
						//获取下载电影的图片列表
						ArrayList<PicInfo> pList = excuteJson(content,movieid);
						//加入电影下载队列
						AppApplication.getInstance().addMovie(movieid, pList);
						
						//int curPage = AppApplication.getInstance().getCurPage();
						//int curMovie = AppApplication.getInstance().getCurMovie();
						
						DownInfo di = AppApplication.getInstance().getDMap().get(movieid);
						//di.setCurpage(0);
						di.setSize(pList.size());
						//设置下载中状态
						di.setState(1);
						
						long rowid = DBHelper.getInstance(DownService.this).updateDownInfoSize(movieid, di.getCurpage(), di.getSize());
						if(rowid==1)
						{
							Logger.info("数据库更新图片数组大小成功1");
						}

						//更新界面
						Intent uiintent = new Intent(Tag.UPDATEUI);
				        sendBroadcast(uiintent); 

				        
				        //开始下载
				        Intent service = new Intent(Tag.START);
						service.putExtra("action", Tag.DownPic);
						service.putExtra("movieid", movieid);
					    startService(service);
					        

					}
	        		
				});
	        }else{
	        	//本地有缓存
	        	ArrayList<PicInfo> pList = excuteJson(cacheMoviePics,movieid);
	        	//Logger.info(":"+pList.size());
	        	//加入电影下载队列
				AppApplication.getInstance().addMovie(movieid, pList);
	        	
	        	
				DownInfo di = AppApplication.getInstance().getDMap().get(movieid);
				di.setSize(pList.size());
				di.setState(1);
				
				long rowid = DBHelper.getInstance(DownService.this).updateDownInfoSize(movieid, di.getCurpage(), di.getSize());
				if(rowid==1)
				{
					Logger.info("数据库更新图片大小成功2");
				}
				
				
				//更新界面
				Intent uiintent = new Intent(Tag.UPDATEUI);
		        sendBroadcast(uiintent); 
				
		        
		        //开始下载
		        Intent service = new Intent(Tag.START);
				service.putExtra("action", Tag.DownPic);
				service.putExtra("movieid", movieid);
			    startService(service);

	        }
		}else if(action.equals(Tag.DownStop))
		{
			String movieid = intent.getStringExtra("movieid");
			AppApplication.getInstance().getDMap().get(movieid).setState(0);
			//更新界面
			Intent uiintent = new Intent(Tag.UPDATEUI);
	        sendBroadcast(uiintent); 
	        
	        stopSelf();
		}
	}	
	
	
	public ArrayList<PicInfo> excuteJson(String rejson,String movieid)
	{
    	ArrayList<PicInfo> pList = new ArrayList<PicInfo>();
		try {
			JSONObject result = new JSONObject(rejson);
			int status = result.getInt("status");
			if(status==1)
			{
				ConfigCache.setUrlCache(rejson, AppConfig.GETMOVIEINFO+movieid);    
				JSONArray list = result.getJSONArray("story");
				for(int i=0;i<list.length();i++)
				{
					JSONObject obj = list.getJSONObject(i);
					PicInfo pinfo = new PicInfo();
					pinfo.setId(obj.getString("id"));
					pinfo.setImage(obj.getString("image"));
					pinfo.setIntro(obj.getString("intro"));
					pinfo.setpIndex(obj.getString("pindex"));
					pList.add(pinfo);
				}
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		return pList;
	}
	

	public long getDirSize(String movieid)
	{
		File ff = new File(Environment.getExternalStorageDirectory().getPath()+AppConfig.MOVIESDIR+movieid+"/");		
        long filesize = 0;
		try {
			filesize = FileUtils.getFileSize(ff);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			
		}
		return filesize;
	}
	
	

}
